import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/refresh_order_event.dart';
import 'package:flutter_rider/event/refresh_outside_list_event.dart';
import 'package:flutter_rider/generated/assets.dart';
import 'package:flutter_rider/kit/loc_kit.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/page/image_viewer_page.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/dialog/loading_dialog.dart';
import 'package:flutter_rider/main/widgets/pop/pop_car_keyboard.dart';
import 'package:flutter_rider/main/widgets/pop/pop_outside_stations.dart';
import 'package:flutter_rider/module/mine/api/truck_api.dart';
import 'package:flutter_rider/module/mine/models/truck_model.dart';
import 'package:flutter_rider/module/mine/provider/number_car_provider.dart';
import 'package:flutter_rider/module/mine/provider/outside_car_provider.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/utils/toast.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main/widgets/ext/u_background.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/utils/upload_image_helper.dart';

class OutsideDetailWidget extends ConsumerStatefulWidget {
  bool isAddCar;
  TruckModel? truck;
  OutsideDetailWidget(
    this.isAddCar, {
    this.truck,
    Key? key,
  }) : super(key: key);
  @override
  ConsumerState createState() => _OutsideDetailWidgetState();
}

class _OutsideDetailWidgetState extends ConsumerState<OutsideDetailWidget> {
  late UploadImageHelper _uploadHelper;
  final _describeTextController = TextEditingController();
  @override
  void initState() {
    super.initState();
    _uploadHelper = UploadImageHelper(context, maxImages: 3);
    if (widget.truck != null) {
      _describeTextController.text = widget.truck!.remark;
    }
    if (widget.isAddCar) {
      ref.read(numberCarProvider.notifier).addVaule("川");
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(8.rpx)),
      ),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        20.hspace,
        Container(
          alignment: Alignment.center,
          child: Row(children: [
            16.wspace,
            InkWell(
                child: SvgPicture.asset(R.image_left,
                    width: 24.rpx, height: 24.rpx),
                onTap: () {
                  NavigatorUtils.goBack(context);
                }),
            // ),
            4.wspace,
            Expanded(
                child: Container(
              alignment: Alignment.center,
              child:
                  UText.get("车辆详情", Colors.black, 20.rpx, fw: FontWeight.bold),
            )),
            4.wspace,
            24.wspace,
            16.wspace,
          ]),
        ),
        18.hspace,
        Expanded(
            child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              RichText(
                text: TextSpan(
                    text: "车牌号",
                    style: TextStyle(
                        color: UIColor.color_t16,
                        fontSize: 16.rpx,
                        fontWeight: FontWeight.w600),
                    children: [
                      TextSpan(
                        text: "*",
                        style: TextStyle(
                            color: UIColor.color_none,
                            fontSize: 16.rpx,
                            fontWeight: FontWeight.w600),
                      )
                    ]),
              ).padding(EdgeInsets.only(left: 16.rpx, bottom: 12.rpx)),
              _numberCar(),
              0.5.hLine16,
              _showStations(),
              0.5.hLine16,
              widget.isAddCar
                  ? ValueListenableBuilder<List<AssetEntity>>(
                      valueListenable: _uploadHelper.getValueNotifier(),
                      builder: (context, value, child) {
                        Future.delayed(const Duration(milliseconds: 500), () {
                          // if (mounted) {
                          ref.read(outsideImageProvider.state).state =
                              _uploadHelper.getImageUrls().isNotEmpty;
                          // }
                        });
                        return _renderUploadImage(value);
                      })
                  : _renderImage(widget.truck!.images),
              0.5.hLine16,
              _renderRemark(),
            ],
          ),
        )),
        widget.isAddCar ? _submitBtn() : _deleteBtn()
      ]),
    );
  }

  Widget _numberCar() {
    return Consumer(builder: (context, ref, child) {
      var numberCarModel = ref.watch(numberCarProvider);
      return Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        mainAxisSize: MainAxisSize.max,
        children: [
          _numberWidget(numberCarModel.inputIndex == 0, numberCarModel.value0),
          _numberWidget(numberCarModel.inputIndex == 1, numberCarModel.value1),
          Container(
            height: 8.rpx,
            width: 8.rpx,
            padding: EdgeInsets.all(10.rpx),
            decoration: BoxDecoration(
              color: UIColor.color_black,
              borderRadius: BorderRadius.circular(4.rpx),
            ),
          ),
          _numberWidget(numberCarModel.inputIndex == 2, numberCarModel.value2),
          _numberWidget(numberCarModel.inputIndex == 3, numberCarModel.value3),
          _numberWidget(numberCarModel.inputIndex == 4, numberCarModel.value4),
          _numberWidget(numberCarModel.inputIndex == 5, numberCarModel.value5),
          _numberWidget(numberCarModel.inputIndex == 6, numberCarModel.value6),
          _xnyNumberWidget(
              widget.isAddCar
                  ? numberCarModel.inputIndex <= 7
                  : numberCarModel.inputIndex <= 8,
              numberCarModel.value7),
        ],
      )
          .padding(EdgeInsets.only(left: 16.rpx, right: 16.rpx, bottom: 16.rpx))
          .onTap(() {
        if (widget.isAddCar) {
          OpenUtils.popKey(context, const CarKeyboard());
        }
      });
    });
  }

  Widget _numberWidget(bool isEnter, String value) {
    return isEnter
        ? Container(
            width: 32.rpx,
            height: 40.rpx,
            alignment: Alignment.center,
            padding: EdgeInsets.all(8.rpx),
            decoration: BoxDecoration(
              color: UIColor.colorInputBg,
              borderRadius: BorderRadius.circular(4.rpx),
              //边框线宽、颜色
              border: Border.all(width: 1.0, color: UIColor.color_primary),
            ),
          )
        : Container(
            width: 32.rpx,
            height: 40.rpx,
            alignment: Alignment.center,
            padding: EdgeInsets.all(8.rpx),
            decoration: BoxDecoration(
              color: UIColor.color_input,
              borderRadius: BorderRadius.circular(4.rpx),
            ),
            child: UText.get(value, UIColor.color_black, 16.rpx,
                fw: FontWeight.bold),
          );
  }

  Widget _xnyNumberWidget(bool isEnter, String value) {
    return isEnter
        ? Container(
            width: 32.rpx,
            height: 40.rpx,
            padding: EdgeInsets.only(
                left: 4.rpx, right: 4.rpx, top: 5.rpx, bottom: 5.rpx),
            decoration: BoxDecoration(
              color: UIColor.color_bg,
              borderRadius: BorderRadius.circular(4.rpx),
            ),
            child: Column(
              children: [
                UText.get("+", UIColor.color_primary, 14.rpx,
                    fw: FontWeight.bold),
                UText.get("新能源", UIColor.color_black, 6.rpx)
              ],
            ),
          )
        : Container(
            width: 32.rpx,
            height: 40.rpx,
            alignment: Alignment.center,
            padding: EdgeInsets.all(8.rpx),
            decoration: BoxDecoration(
              color: UIColor.color_input,
              borderRadius: BorderRadius.circular(4.rpx),
              //边框线宽、颜色
              border: Border.all(width: 1.0, color: UIColor.color_primary),
            ),
            child: UText.get(value, UIColor.color_black, 16.rpx,
                fw: FontWeight.bold),
          );
  }

  Widget _showStations() {
    return Row(children: [
      RichText(
        text: TextSpan(
            text: "停靠点",
            style: TextStyle(
                color: UIColor.color_t16,
                fontSize: 16.rpx,
                fontWeight: FontWeight.w600),
            children: [
              TextSpan(
                text: "*",
                style: TextStyle(
                    color: UIColor.color_none,
                    fontSize: 16.rpx,
                    fontWeight: FontWeight.w600),
              )
            ]),
      ),
      Consumer(
        builder: (context, ref, child) {
          return Container(
                  alignment: Alignment.centerRight,
                  child: UText.get(ref.watch(stopStationProvider).name,
                      UIColor.color_t16, 16.rpx))
              .expand;
        },
      ),
      widget.isAddCar
          ? SvgPicture.asset(Assets.imageChevronRight,
              width: 24.rpx, height: 24.rpx)
          : ScreenFit.empty
    ]).padding(EdgeInsets.all(16.rpx)).onTap(() {
      if (widget.isAddCar) {
        OpenUtils.pop4(context, OutsideStationsWidget());
      }
    });
  }

  Widget _renderUploadImage(List<AssetEntity> list) {
    var width = (MediaQuery.of(context).size.width - 80.rpx) / 3;
    List<Widget> children = [];
    for (var element in list) {
      children.add(SizedBox(
        width: width,
        height: width,
        child: Stack(
          children: [
            Image(
                image: AssetEntityImageProvider(element),
                fit: BoxFit.cover,
                width: width,
                height: width),
            GestureDetector(
              onTap: () {
                _uploadHelper.remove(element);
              },
              child: Align(
                alignment: Alignment.topRight,
                child: SvgPicture.asset(R.image_delete,
                    width: 28.rpx, height: 28.rpx),
              ),
            ),
          ],
        ),
      ));
    }
    return UBackground.getItemBlock([
      RichText(
        text: TextSpan(
            text: "车辆照片",
            style: TextStyle(
                color: UIColor.color_t16,
                fontSize: 16.rpx,
                fontWeight: FontWeight.w600),
            children: [
              TextSpan(
                text: "*",
                style: TextStyle(
                    color: UIColor.color_none,
                    fontSize: 16.rpx,
                    fontWeight: FontWeight.w600),
              )
            ]),
      ).padding(EdgeInsets.only(
        left: 2.rpx,
      )),
      SizedBox(height: 10.rpx),
      Wrap(
        spacing: 10.rpx,
        runSpacing: 10.rpx,
        children: children,
      ),
      SizedBox(height: 10.rpx),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          MaterialButton(
            height: 32.rpx,
            minWidth: 120.rpx,
            color: UIColor.color_primary,
            elevation: 0,
            highlightColor: Colors.transparent,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(16.rpx)),
            ),
            child: UText.get("拍摄", Colors.white, 14.rpx),
            onPressed: _uploadHelper.takePhoto,
          ),
          MaterialButton(
            height: 32.rpx,
            minWidth: 120.rpx,
            color: UIColor.color_primary,
            // elevation: 0,
            highlightColor: Colors.transparent,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(16.rpx)),
            ),
            child: UText.get("手机相册选择", Colors.white, 14.rpx),
            onPressed: _uploadHelper.pickImage,
          ),
        ],
      )
    ]);
  }

  Widget _renderImage(List list) {
    var width = (MediaQuery.of(context).size.width - 80.rpx) / 3;
    List<Widget> children = [];
    for (var i = 0; i < list.length; i++) {
      // for (var element in list) {
      children.add(SizedBox(
        width: width,
        height: width,
        child: Stack(
          children: [
            Image.network(list[i],
                    fit: BoxFit.cover, width: width, height: width)
                .onTap(() {
              OpenUtils.open(context, ImageViewerPage(list, index: i));
            }),
          ],
        ),
      ));
    }
    return UBackground.getItemBlock([
      RichText(
        text: TextSpan(
            text: "车辆照片",
            style: TextStyle(
                color: UIColor.color_t16,
                fontSize: 16.rpx,
                fontWeight: FontWeight.w600),
            children: [
              TextSpan(
                text: "*",
                style: TextStyle(
                    color: UIColor.color_none,
                    fontSize: 16.rpx,
                    fontWeight: FontWeight.w600),
              )
            ]),
      ).padding(EdgeInsets.only(
        left: 2.rpx,
      )),
      SizedBox(height: 10.rpx),
      Wrap(
        spacing: 10.rpx,
        runSpacing: 10.rpx,
        children: children,
      ),
    ]);
  }

  Widget _renderRemark() {
    return Container(
        padding: EdgeInsets.only(
            left: 16.rpx, top: 16.rpx, right: 16.rpx, bottom: 12.rpx),
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child: Column(
          children: [
            Container(
              // padding: EdgeInsets.only(top: 12.rpx, bottom: 12.rpx),
              alignment: Alignment.centerLeft,
              child: UText.get("备注信息", UIColor.color_t1, 16.rpx,
                  textAlign: TextAlign.left, fw: FontWeight.w600),
            ),
            // 12.hspace,
            TextField(
                style: TextStyle(fontSize: 14.rpx),
                controller: _describeTextController,
                keyboardType: TextInputType.multiline,
                maxLines: null,
                maxLength: 60,
                enabled: widget.isAddCar,
                decoration: InputDecoration(
                    hintText: widget.isAddCar ? "请输入备注信息（选填）" : "",
                    hintStyle: TextStyle(
                        color: Colors.black.withOpacity(0.4), fontSize: 14.rpx),
                    border: InputBorder.none)),
          ],
        ));
  }

  Widget _deleteBtn() {
    return Padding(
      padding: EdgeInsets.only(
          top: 16.rpx,
          left: 12.rpx,
          right: 12.rpx,
          bottom: ScreenUtil.getInstance().bottomBarHeight + 10.rpx),
      child: UText.getBkButton(
        "删除车辆",
        16.rpx,
        bkColor: UIColor.color_none,
        radius: 24.rpx,
        width: double.infinity,
        height: 48.rpx,
        onPressed: _onClickDelete,
      ),
    );
  }

  _onClickDelete() {
    CustomAlertDialog.showConfirmDialog(context,
        title: "删除车辆信息",
        content:
            "确认删除   ${ref.read(numberCarProvider.notifier).getPointNumberCar()}  车辆信息吗？",
        confirmText: '确认删除',
        confirmTextColor: UIColor.color_none, onConfirm: () {
      var dialog = LoadingDialog(context);
      dialog.show(text: "正在删除中");
      if (widget.truck == null) return;

      // var json = {};
      // json["id"] = widget.truck!.id.toString();
      Api.deletex(
          context, "${TruckApi.truckDelete}?id=${widget.truck!.id.toString()}",
          // data: json,
          progress: false,
          success: (data) {
            dialog.hide();
            eventBus.fire(RefreshOutsideList());
            NavigatorUtils.goBack(context);
            Toast.show(context);
          },
          failTip: "提交失败",
          fail: (_) {
            dialog.hide();
          });
    });
  }

  Widget _submitBtn() {
    var isDisabled = ref.watch(submitOutsideProvider);
    return Padding(
      padding: EdgeInsets.only(
          top: 16.rpx,
          left: 12.rpx,
          right: 12.rpx,
          bottom: ScreenUtil.getInstance().bottomBarHeight + 10.rpx),
      child: MaterialButton(
        minWidth: double.infinity,
        height: 40.rpx,
        onPressed: isDisabled ? _onClickSubmit : null,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(24.rpx),
        ),
        color: UIColor.color_primary,
        disabledColor: Colors.black.withOpacity(0.26),
        child: UText.get("提交", Colors.white, 14.rpx),
      ),
    );
  }

  _onClickSubmit() {
    Log.i("提交的定位信息-------> ${ref.read(positionProvider)}");
    CustomAlertDialog.showConfirmDialog(context,
        title: "提交车辆信息",
        content:
            "确认提交  ${ref.read(numberCarProvider.notifier).getPointNumberCar()}  车辆信息吗？",
        confirmText: '确认提交', onConfirm: () {
      var json = {};
      var positionInfo = ref.read(positionProvider);
      // var positionInfo = LocKit.instance.getData();
      // if (positionInfo.isNotEmpty) {
      json["lat"] = positionInfo.latitude.toString();
      json["lng"] = positionInfo.longitude.toString();
      // }
      json["park_id"] = ref.read(stopStationProvider).id; //停靠点ID
      json["remark"] = _describeTextController.text;
      json["images"] = _uploadHelper.getImageUrls();
      json["plate_no"] = ref.read(numberCarProvider.notifier).getNumberCar();
      var dialog = LoadingDialog(context);
      dialog.show(text: "正在提交中");
      Api.submitx(context, TruckApi.truckAdd,
          data: json,
          progress: false,
          success: (data) {
            dialog.hide();
            eventBus.fire(RefreshOutsideList());
            NavigatorUtils.goBack(context);
          },
          failTip: "提交失败",
          fail: (_) {
            dialog.hide();
          });
    });
  }
}
